//封装axios的请求
import axios from "axios";
import {ElMessage} from "element-plus";
import qs from "qs";

//创建axios的实例
const instance = axios.create({
    baseURL: 'http://localhost:8081/boss',
    timeout: 5000
})

//封装post请求
export function doPostJson(path, parameters) {
    return instance({
        url: path,
        method: 'POST',
        data: parameters
    })
}

//提交的是name=value & name = value 格式的参数
//qs是一个库，将{"a":10,"b":20}的格式转为  a10=&b=20
export function doPostForm(path,parameters){
    return instance({
        url:path,
        method:'POST',
        data:qs.stringify(parameters)
    })
}


//封装get请求
export function doGet(path, parameters) {
    return instance({
        url: path,
        method: 'GET',
        params: parameters
    })
}

//请求拦截器，增加operatorId参数
instance.interceptors.request.use(
    (req) => {
        const sessionCache = sessionStorage.getItem('BOSS_TOKEN')
        if (sessionCache) {
            let sessionObject = JSON.parse(sessionCache)
            req.headers.operatorId = sessionObject.operatorId
        }
        return req
    },
    (err) => {
        console.log('请求拦截器错误：' + err)
    }
)

//处理服务器返回的错误信息
instance.interceptors.response.use(
    (resp) => {
        if (resp.data.code > 1000) {
            ElMessage.warning(resp.data.msg)
        }
        return resp
    },
    (err) => {
        console.log('应答拦截器错误' + err)
    }
)
